package com.ly.thread;


class Shop {
    private static int number = 0;

    public synchronized void create() throws InterruptedException {
        while(number != 0 ) {
            this.wait();
        }
        number++;

        this.notifyAll();
        System.out.println(Thread.currentThread().getName()+" "+number);
    }

    public synchronized void sell() throws InterruptedException {
        while(number == 0) {
            this.wait();
        }
        number--;

        this.notifyAll();
        System.out.println(Thread.currentThread().getName()+" "+number);
    }
}




public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        Shop shop = new Shop();
        for(int i=0;i<10;i++) {
            new Thread(() -> {
                try {
                    shop.create();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"A").start();
            new Thread(() -> {
                try {
                    shop.sell();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"B").start();
            new Thread(() -> {
                try {
                    shop.create();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"C").start();
            new Thread(() -> {
                try {
                    shop.sell();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"D").start();
        }
    }
}
